<?php
 
namespace Modules\ShopAdmin\Models;
use Modules\AuthAdmin\Services\QueryService;
use Modules\AuthAdmin\Services\CommonService;
use Modules\ShopAdmin\Models\AuthArea as AuthAreaModel;
use Modules\AuthAdmin\Models\AuthImage as AuthImageModel;
use Illuminate\Support\Facades\DB; 
use EasyWeChat\Factory;
class ShopOrder extends BaseApiModel
{
	/**
     * @name  关联订单详情
     */
    public function order_info_to()
    {
        return $this->hasMany('Modules\ShopAdmin\Models\ShopOrderInfo','order_id','id');
    }
	/**
     * @name  关联订单申诉
     */
    public function order_complain_to()
    {
        return $this->hasMany('Modules\ShopAdmin\Models\ShopOrderComplain','order_id','id');
    }
	/**
     * @name  关联用户
     */
    public function user_to()
    {
        return $this->belongsTo('Modules\ShopAdmin\Models\ShopUser','user_id','id');
    }
	/**
     * @name   付款时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getPayTimeAttribute($value)
    {
        return $value?$value:'';
    }
	/**
     * @name   发货时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getDeliveryTimeAttribute($value)
    {
        return $value?$value:'';
    }
	/**
     * @name   评价时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getReceiveTimeAttribute($value)
    {
        return $value?$value:'';
    }
	/**
     * @name   创建时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getCreatedAtAttribute($value)
    {
        return $value?$value:'';
    }
	/**
     * @name   备注为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getCommentAttribute($value)
    {
        return $value?$value:'';
    }
	/**
     * @name  获取订单状态列表
     */
	private function status_list(){
		return [
			'1'=>'待付款',
			'2'=>'待发货',
			'3'=>'待收货',
			'4'=>'待评价',
			'5'=>'订单已取消',
			'6'=>'申诉中','7'=>'申诉失败',
			'8'=>'申诉完成',
			'9'=>'已完成'
		];
	}
	/**
	 * @name  订单列表
	 * @param  data array 搜索数据
	 * @return  JSON
	 */
	public function list_data($data){
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data,'user_name');
		if (!empty($data['user_phone'])){
			$model = $model->where('user_phone','like','%' . $data['user_phone'] . '%');	
		} 
		if (!empty($data['order_no'])){
			$model = $model->where('order_no','like','%' . $data['order_no'] . '%');	
		} 
		if (!empty($data['pay_time'])){
			$model = $model->whereBetween('pay_time',explode('|',$data['pay_time']));
		}
		if (!empty($data['delivery_time'])){
			$model = $model->whereBetween('delivery_time',explode('|',$data['delivery_time']));
		}
		$list = $model->select('id','user_id','order_no','status','total_money','total_num','user_name','user_address','user_phone','pay_time','delivery_time','comment')
				->whereHas('user_to',function($query)use ($data){
					if(!empty($data['nick_name'])){
						$query->where('nick_name', 'like', '%' . $data['nick_name'] . '%');
					}
				})
				->with([
					'user_to'=>function($query){
						$query->select('id','nick_name');
					},
					'order_info_to'=>function($query){
						$query->select('id','order_id','product_id','specs','num','money','postage');
					},
					'order_info_to.product_to'=>function($query){
						$query->select('id','name');
					}
				])
				->withCount([
					'order_complain_to'
					//=>function($query){
					//	$query->where(['status'=>0]);
					//}
				])
				->orderBy('id','desc')
				->paginate($data['pagesize'])
				->toArray();
		$status_list = $this->status_list();		
		foreach($list['data'] as $k=>$v){
			$list['data'][$k]['order_info'] = '';
			foreach($v['order_info_to'] as $k1=>$v1){
				$list['data'][$k]['order_info'] = $list['data'][$k]['order_info'] . '商品：' . $v1['product_to']['name'] . ',规格：' . ($v1['specs']?$v1['specs']:'无') . ',数量：' . $v1['num'] . ',单价：' . $v1['money'] . ',单个邮费：' . $v1['postage'] . ';';
			}
			$list['data'][$k]['status_name'] = $status_list[$v['status']];
			unset($list['data'][$k]['order_info_to']);
		}		
		return $this->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);
	}
	
	/**
	 * @name  编辑地址页面
	 * @param  id int 订单id	
	 * @return  JSON
	 */
	public function edit_address($id){
		$info = $this->select('id','user_name','user_address','user_phone','province_id','province_name','city_id','city_name','county_id','county_name')->find($id);
		$area_list = (new AuthAreaModel())->get_area();
		return $this->api_success(['data'=>[
			'info'=>$info,
			'area_list'=>$area_list
		]]);
	}
	/**
	 * @name  编辑地址提交
	 * @param  data array 修改数据	
	 * @return  JSON
	 */
	public function edit_update($data){
		$id = $data['id'];
		unset($data['id']);
		if ($this->where('id',$id)->update($data)!==false){
			return $this->api_success(['msg'=>'修改成功！']);
        }else{
			return $this->api_error(['msg'=>'修改失败！']);
		}
	}
	/**
	 * @name  发货
	 * @param  id array 订单id	
	 * @return  JSON
	 */
	public function order_status($id){
		$info = $this->select('id','status','user_id','order_no','total_money','user_address')->with([
					'user_to'=>function($query){
						$query->select('id','xcx_open_id');
					}
				])
				->where(['id'=>$id])	
				->first()
				->toArray();
		if($info['status']!=2){
			return $this->api_error(['msg'=>'发货失败！']);
		}
		$date = date('Y-m-d H:i:s');
		if ($this->where('id',$id)->update(['delivery_time'=>$date,'status'=>3])){
			$config = config('wechat.mini_program.default'); 
			$app = Factory::miniProgram($config);
			$data = [
				'template_id' => config('shopadmin.order_shipments'), // 所需下发的订阅模板id
				'touser' => $info['user_to']['xcx_open_id'],     // 接收者（用户）的 openid
				'page' => '/pages/order/order',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
				'data' => [        
					'character_string1' => [
						'value' => $info['order_no'],
					],
					'amount2' => [
						'value' => $info['total_money'],
					],
					'time5' => [
						'value' => $date,
					],
					'thing4' => [
						'value' => $info['user_address'],
					],
				],
			];
			$app->subscribe_message->send($data);
			return $this->api_success(['msg'=>'发货成功！']);
        }else{
			return $this->api_error(['msg'=>'发货失败！']);
		}
	}
	/**
	 * @name  订单详情
	 * @param  id int 订单id		
	 * @return  JSON
	 */
	public function order_detail($id){
		$info = $this->with([
					'user_to'=>function($query){
						$query->select('id','nick_name');
					},
					'order_info_to'=>function($query){
						$query->select('id','order_id','product_id','specs','num','money','postage');
					},
					'order_info_to.product_to'=>function($query){
						$query->select('id','name','image_id');
					}
				])
				->where(['id'=>$id])	
				->first()
				->toArray();
		$info['nick_name']= $info['user_to']['nick_name'];		
		$info['status'] = $this->status_list()[$info['status']];
		return $this->api_success(['data'=>$info]);
	}
	/**
	 * @name  退款页面
	 * @param  id int 订单id		
	 * @return  JSON
	 */
	public function order_refund_info($id){
		$info = $this->select('id','total_money','order_no','serial_number')
				->where(['id'=>$id])	
				->first()
				->toArray();
		return $this->api_success(['data'=>$info]);
	}
	/**
	 * @name  退款数据处理
	 * @param  data array 退款数据		
	 * @return  JSON
	 */
	public function order_refund($data){
		$config = config('wechat.payment.default'); 
		$payment = Factory::payment($config);
		$order_info = $this->find($data['id'])->toArray();
		$CommonService = new CommonService();	
		$refund_no = $CommonService->make_order_no();
		$res = $this->where(['id'=>$data['id']])->update([
			'refund_no'=>$refund_no,
			'refund_comment'=>$data['refund_comment'],
			'refund_money'=>$data['refund_money']
		]);
		if($res){
			$result = $payment->refund->byOutTradeNumber($order_info['order_no'], $refund_no,$order_info['total_money']*100,$data['refund_money']*100, [
				'refund_desc' => $data['refund_comment'],
				'notify_url' => $CommonService->get_http_type().'/api/v1/shop_api/wx/refund'
			]);
			if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
				return $this->api_success(['msg'=>'退款成功！']);
			}
		}
		return $this->api_error(['msg'=>'退款失败！']);
	}
	/**
	 * @name  微信退款回调
	 */
	public function refund(){
		$CommonService = new CommonService();	
		$options = config('wechat.payment.default');
		$options['notify_url'] = $CommonService->get_http_type().'/api/v1/shop_api/wx/refund';
		unset($options['cert_path'],$options['key_path']);
		$payment = Factory::payment($options);
		$response = $payment->handleRefundedNotify(function ($message, $reqInfo, $fail) {
            $order = $this->where('order_no',$reqInfo['out_trade_no'])->first()->toArray();
            if (!$order || $order['status']==5) { 
                return true; 
            }
            if($message['return_code']=='SUCCESS'){
                if($reqInfo['refund_status']=='SUCCESS'){
                   $res = $this->where(['id'=>$order['id']])->update([
						'status'=>5
				   ]);
				   if(!$res){
					   return $fail('error');
				   }
                }else{
                    return $fail('error');
                }
            }
            return true; // 返回 true 告诉微信“我已处理完成”
            // 或返回错误原因 $fail('参数格式校验错误');
        });
        return $response;
	}
}
